package com.emm.yixun.website.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;

import com.emm.yixun.common.model.User;
import com.emm.yixun.common.utils.WebUtil;
import com.emm.yixun.website.common.utils.security.ShiroUtil;

/**
 * 验证是否已经登录，过滤器
 * @author ThinkPad
 *
 */
public class UserTokenCheckFilter implements Filter {
    
	@Override
	public void destroy() {
		
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain arg2) throws IOException, ServletException {
		HttpServletRequest req=(HttpServletRequest) request;
		HttpServletResponse res=(HttpServletResponse) response;
		//过滤静态资源
		String requestURI=req.getRequestURI();
		User user=null;
		try {
			user = ShiroUtil.getCurrentUser();
		} catch (Exception e) {
		}
		if(!noCheck(requestURI) && null!=user){
			boolean isToLogin=WebUtil.isToLogin(req,user.getUserPhone());
			//检查当前终端是否需要重新登陆
			if(isToLogin){
				Subject currentUser = SecurityUtils.getSubject();
		        currentUser.logout();
			}
		}
		arg2.doFilter(req, res);	
	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {
		
	}
	
	//检查是否为不需要拦截做登陆验证的url
	private boolean noCheck(String url){
		boolean isOk=false;
		if(url.indexOf("/resources/")!=-1){
			isOk=true;
		}
		
		if(url.indexOf("/static/")!=-1){
			isOk=true;
		}
		if(url.indexOf("/loginIndex")!=-1){
			isOk=true;
		}
		
		if(url.indexOf("/system_login")!=-1){
			isOk=true;
		}
		if(url.indexOf("/verifyCode/")!=-1){
			isOk=true;
		}
		if(url.indexOf(".ico")!=-1){
			isOk=true;
		}
		
		return isOk;
	}


}
